import jwt
from functools import wraps
from applications.config import Config
from applications.common.utils.http import *
from werkzeug.local import LocalProxy
from datetime import datetime

ALGORITHM = 'HS256'

current_user = LocalProxy(lambda: token_parse(request.headers.get(Config.TOKEN_NAME)))


# 生成token
def token_create(user_id: int, time_out=7 * 24 * 60 * 60):
    now = int(datetime.now().timestamp())
    return jwt.encode({
        'user_id': user_id,
        'iat': now,  # 产生token时的时间戳
        'exp': now + time_out  # token过期时间戳
    }, Config.SECRET_KEY, algorithm=ALGORITHM)


# 解析token
def token_parse(token):
    if token is None or token == '':
        return None
    return jwt.decode(token, Config.SECRET_KEY, algorithms=ALGORITHM)


def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # print(f"<login_required>  'current_user' : {current_user}")
        return func(*args, **kwargs)

    return wrapper


def authorize(permission: str = ''):
    """
    用户权限判断，用于判断目前会话用户是否拥有访问权限。

    :param permission: 权限标识
    :type permission: str
    """

    def decorator(func):
        @login_required
        @wraps(func)
        def wrapper(*args, **kwargs):
            # print(f"<authorize> authorize : {permission}")
            if permission == "deny":
                return result_fail("权限不足")
            else:
                return func(*args, **kwargs)

        return wrapper

    return decorator
